import {
  defineStore
} from 'pinia'
import {
  get,
  wxLogin
} from '../utils/helper.js'
const user = defineStore({
  id: 'user',
  state: () => ({
    isReady: null,
    onReady: null,
    isLogin: !!uni.getStorageSync('token'), // 登录状态
    info: {}, // 用户信息
    authType: 'smsLogin'
  }),

  actions: {
    /**
		 * pinia-user 初始化
		 */
    async init() {
      if (this.isLogin) {
        await this.getInfo()
      } else {
        // #ifdef MP
        const { code } = await wxLogin()
        const res = await get('/Login/login', { code })
        await this.setToken(res.data.token)
        // #endif
      }
      typeof this.onReady === 'function' && this.onReady()
      return Promise.resolve({
        info: this.info
      })
    },
    /**
		 * pinia-user 设置 token
		 */
    async setToken(token = '') {
      uni.setStorageSync('token', token)
      this.isLogin = true
      const info = await this.getInfo()
      return Promise.resolve({
        token,
        info
      })
    },
    /**
		 * pinia-user 清除 token
		 */
    clearToken() {
      uni.removeStorageSync('token')
      this.isLogin = false
      this.info = {}
    },
    /**
		 * pinia-user 获取个人信息
		 */
    async getInfo() {
      return Promise.resolve({})
      const [err, res] = await get('/User/index', {}, {
        isAsync: true
      })
      if (err) {
        return Promise.reject({
          msg: err.msg
        })
      }
      this.info = res.data

      return Promise.resolve(res.data)
    },
    /**
		 * pinia-user 登出
		 */
    async logout(force = false) {
      this.setToken()
    },

    setAuthType(value = '') {
      this.authType = value
    }
  }
})

export default user
